package com.guaoran.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.guaoran.utils.HttpClient;
import com.guaoran.utils.Response;
import com.guaoran.utils.WeixinSupport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/1/14 12:42
 */
@Controller
@Slf4j
@RequestMapping("/weixin")
public class WeixinController {
    @Value("${wechat.mpAppId}")
    private String mpAppid;
    @Value("${wechat.mpAppSecret}")
    private String mpAppsecret;
    /*获取域名+项目名*/
    @Value("${domainName}")
    private String domainName;
    /*获取微信授权认证后重定向的url地址*/
    @Value("${wechat.authorize.redirectURL}")
    private String redirectURL;


    /**
     * 微信授权认证
     * @param code
     * @param state
     * //http://xxx/get-weixin-code.html?appid=wx64274a7212f360a7&redirect_uri=http%3A%2F%2Fguaoran.nat300.top%2Fspringboot%2Fweixin%2Fauthorize&response_type=code&scope=snsapi_userinfo&state=http://www.baidu.com#wechat_redirect
     * @return
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam ("code") String code,@RequestParam("state") String state){
        log.info("authorize...code={},state={}",code,state);
        try {
            //1.接收到code，获取access_token
            String getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+mpAppid+"&secret="+mpAppsecret+"&code="+code+"&grant_type=authorization_code";
            log.info("getAccessToken...getAccessTokenUrl={}",getAccessTokenUrl);
            HttpClient http = new HttpClient();
            Response accessTokenRes = http.get(getAccessTokenUrl);
            String accessTokenStr = accessTokenRes.asString();
            log.info("getAccessToken...accessTokenStr="+accessTokenStr);
            JSONObject accessTokenObj = JSONObject.parseObject(accessTokenStr);
            String accessToken = String.valueOf(accessTokenObj.get("access_token"));
            String openid = String.valueOf(accessTokenObj.get("openid"));
            //2.拉取用户信息(需scope为 snsapi_userinfo)
            String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
            Response userInfoRes = http.get(getUserInfoUrl);
            String userInfoStr = userInfoRes.asString();
            log.info("authorize...getUserInfo=" + userInfoStr);
            JSONObject userInfoObj = JSONObject.parseObject(userInfoStr);
            Object errcode = userInfoObj.get("errcode");
            if (errcode != null) {
                throw new Exception(WeixinSupport.getCause(Integer.parseInt(errcode.toString())));
            }
            openid = String.valueOf(userInfoObj.get("openid"));
            String nickname = String.valueOf(userInfoObj.get("nickname"));
            return "redirect:" + redirectURL +"?openid="+openid;
        } catch (Exception e) {
            log.error("authorize...Exception:" + e.toString(), e);
        }
        return null;
    }



}
